package com.goodomen.garbage.common.utils;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Zhao Da
 * @since : 2019/10/23 11:40
 */
public class SolrUtil {

    //solr服务器所在的地址，core0为自己创建的文档库目录
    private final static String SOLR_URL = "http://192.168.10.37:8080/solr/testCore";

    /**
     * 获取客户端的连接
     *
     * @return
     */
    public static HttpSolrClient createSolrServer() {
        return new HttpSolrClient.Builder(SOLR_URL).withConnectionTimeout(10000).withSocketTimeout(60000).build();
    }

    /**
     * 往索引库添加文档
     *
     * @throws SolrServerException
     * @throws IOException
     */
    public static void addDoc(String article) throws SolrServerException, IOException {

        HttpSolrClient solr = createSolrServer();
        solr.addBean(article);

        solr.commit();
        solr.close();
        System.out.println("添加成功");
    }

    /**
     * 根据ID从索引库删除文档
     *
     * @throws SolrServerException
     * @throws IOException
     */
    public void deleteDocumentById(String id) throws SolrServerException, IOException {
        HttpSolrClient solr = createSolrServer();
        solr.deleteById(id);
        solr.commit();
        solr.close();
    }

    /**
     * 根据设定的查询条件进行文档字段的查询
     * @throws Exception
     */
    public static List<String> querySolr(String param) throws Exception {

        SolrQuery query = new SolrQuery();

        //下面设置solr查询参数

        String queryParam = "articleLabel:" + param + " OR " + "articleSummary:" + param + " OR " + "articleTitle:" + param;

        /*StringBuffer sb = new StringBuffer("articleTitle:" + param);

        // articleTitle:黄金 AND channelId:(1 OR 1413627)
        if (channels != null && channels.size() > 0) {
            sb.append(" AND channelId: (");
            sb.append(channels.get(0));

            if (channels.size() > 1) {
                for (int i =1; i < channels.size(); i++) {
                    sb.append(" OR ");
                    sb.append(channels.get(i));
                }
            }
            sb.append(")");
        }*/

        //query.set("q", "*:*");// 参数q  查询所有
        query.set("q", queryParam);//相关查询这个作用适用于联想查询
        //参数df,给query设置默认搜索域，从哪个字段上查找
//        query.set("df", "articleLabel");

        //参数fq, 给query增加过滤查询条件
//        query.addFacetQuery("id:[0 TO 9]");
//        query.addFilterQuery("articleSummary:" + param);

        //参数sort,设置返回结果的排序规则
        query.setSort("id",SolrQuery.ORDER.desc);

        //设置分页参数
        query.setStart(0);
        query.setRows(10);

        //设置高亮显示以及结果的样式
        query.setHighlight(true);
        query.addHighlightField("name");
        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");

        HttpSolrClient solr = createSolrServer();
        //执行查询
        QueryResponse response = solr.query(query);

        //获取返回结果
        SolrDocumentList resultList = response.getResults();

        if (resultList.size() < 1) {
            return null;
        }
/*//获取实体对象形式
        List<ArticleSolrResponse> responses = response.getBeans(ArticleSolrResponse.class);
        List<ArticleDto> articles = new ArrayList<ArticleDto>();
        for (ArticleSolrResponse solrResponse : responses) {
            ArticleDto article = new ArticleDto();
            try {
                String id = solrResponse.getId();
                article.setId(Long.valueOf(id.split("_")[1]));
                article.setContentId(solrResponse.getContentId().get(0));
                article.setChannelId(solrResponse.getChannelId().get(0));
                article.setTitle(solrResponse.getArticleTitle().get(0));
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                article.setCreatedAt(format.parse(solrResponse.getCreatedAt().get(0)));
                if (article.getChannelId() != null && article.getChannelId() == 1) {
                    // 头条
                    article.setSourceType(4);
                } else {
                    article.setSourceType(3);
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            articles.add(article);
        }*/
        return new ArrayList<>();
    }

    public static void main(String[] args) throws Exception {
        SolrUtil solr = new SolrUtil();
        String article = new String();

//        solr.addDoc(article);
        solr.querySolr("国防");

    }

}
